import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, InputNumber, message, Row, Select, Spin } from 'antd';
import { Ref, useEffect, useRef } from 'react';
import { AuthClientManageAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import { addClinetService, editClientService, getClientByIDService } from '../service';
import { RegularExpression } from '@/common/constVariable';
import { TagSelectNew } from '@/components/TagSelectNew';

export const UpdateModal: React.FC<AuthClientManageAPI.IUpdateModal> = ({ checkRows, onClose, reloadManage }) => {
  const [updateForm] = Form.useForm();

  /**
   * modal ref
   */
  const clientUpdateModalRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (clientUpdateModalRef) {
      if (clientUpdateModalRef.current) {
        if (clientUpdateModalRef.current.onModalCancel) {
          clientUpdateModalRef.current.onModalCancel();
        }
      }
    }
  };

  /**
   * 获取详情回调
   * @param res
   */
  const getClientByIDCall = (res: any) => {
    if (res && res?.msgFlag) {
      updateForm?.setFieldsValue({
        ...res?.obj,
      });
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入详情接口
   */
  const { getClientByIDLoading, getClientByIDRun, getClientByIDData } = getClientByIDService(getClientByIDCall);

  /**
   * 初始化
   */
  useEffect(() => {
    if (checkRows?.id) {
      getClientByIDRun(checkRows?.id);
    }
  }, [checkRows?.id]);

  /**
   * 新增编辑接口回调
   * @param res
   */
  const updateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      onCloseModal();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入新增接口 */
  const { addClinetLoading, addClinetRun } = addClinetService(updateCallback);

  /** 引入编辑接口 */
  const { editClientLoading, editClientRun } = editClientService(updateCallback);

  /**保存 */
  const onOk = () => {
    updateForm?.validateFields()?.then((values: any) => {
      if (checkRows?.id) {
        const editPayload: Record<string, any> = {
          ...values,
          id: checkRows?.id,
          versionNum: checkRows?.versionNum,
          isOpen: checkRows?.isOpen,
        };
        editClientRun(editPayload);
      } else {
        const addPayload: Record<string, any> = {
          ...values,
          isOpen: 1,
        };
        addClinetRun(addPayload);
      }
    });
  };

  return (
    <OneModal
      open={true}
      ref={clientUpdateModalRef}
      title={checkRows?.id ? '编辑认证' : '添加认证'}
      width={document.body.clientWidth * 0.4}
      onCancel={onClose}
      bodyStyle={{
        padding: '5px 10px',
      }}
      onOk={onOk}
      centered
      confirmLoading={getClientByIDLoading || addClinetLoading || editClientLoading}
    >
      <Spin spinning={getClientByIDLoading || addClinetLoading || editClientLoading}>
        <div className={pageStyles['fromView-styles']}>
          <Form form={updateForm}>
            <Row>
              <Col span={24}>
                <Form.Item
                  name="name"
                  label="名称"
                  rules={[
                    {
                      required: true,
                      message: '请输入名称',
                    },
                  ]}
                >
                  <Input placeholder="请输入名称" allowClear />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  name="pwd"
                  label="秘钥"
                  rules={[
                    {
                      required: true,
                      message: '请输入秘钥',
                    },
                  ]}
                >
                  <Input placeholder="请输入秘钥" allowClear />
                </Form.Item>
              </Col>
              <TagSelectNew
                formLabel="状态"
                formName="isOpen"
                radioDisabled={true}
                radioList={[
                  {
                    value: 1,
                    name: '启用',
                  },
                  {
                    value: 0,
                    name: '禁用',
                  },
                ]}
                defalultKeys={getClientByIDData?.isOpen}
              />
              <Col span={24}>
                <Form.Item
                  name="clientType"
                  label="类型"
                  rules={[
                    {
                      required: true,
                      message: '请选择类型',
                    },
                  ]}
                >
                  <Select placeholder="请选择类型">
                    <Select.Option value={0} key={0}>
                      WEB应用
                    </Select.Option>
                    <Select.Option value={1} key={1}>
                      移动应用
                    </Select.Option>
                    <Select.Option value={2} key={2}>
                      三方对接
                    </Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  name="tokenSpan"
                  label="token时长"
                  rules={[
                    {
                      required: true,
                      message: '请输入token时长',
                    },
                    {
                      pattern: RegularExpression?.number,
                      message: '只能输入非负整数',
                    },
                  ]}
                  initialValue={0}
                >
                  <InputNumber placeholder="请输入token时长" addonAfter="s" min={0} precision={0} />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  name="refreshSpan"
                  label="刷新时长"
                  rules={[
                    {
                      required: true,
                      message: '请输入刷新时长',
                    },
                    {
                      pattern: RegularExpression?.number,
                      message: '只能输入非负整数',
                    },
                  ]}
                  initialValue={0}
                >
                  <InputNumber placeholder="请输入刷新时长" addonAfter="s" min={0} precision={0} />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  name="scope"
                  label="作用域"
                  rules={[
                    {
                      required: true,
                      message: '请输入作用域',
                    },
                  ]}
                >
                  <Input.TextArea
                    placeholder="请输入作用域"
                    maxLength={200}
                    showCount
                    autoSize={{ minRows: 2, maxRows: 4 }}
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  name="authType"
                  label="授权类型"
                  rules={[
                    {
                      required: true,
                      message: '请输入授权类型',
                    },
                  ]}
                >
                  <Input.TextArea
                    placeholder="请输入授权类型"
                    maxLength={200}
                    showCount
                    autoSize={{ minRows: 2, maxRows: 4 }}
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="redirectUrl" label="重新定向地址">
                  <Input placeholder="请输入重新定向地址" allowClear />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="remark" label="备注">
                  <Input.TextArea placeholder="请输入备注" showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 4 }} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
